/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"encoding/json"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"k8s.io/api/admission/v1beta1"
	"k8s.io/klog"
)

//		 {"op":"add","path":"/spec/Containers","value":[{"image":"webhook-added-image","name":"webhook-added-init-container","resources":{}}]}
//  {"op": "add", "path": "/spec/containers[0]/env"", "value": [{"name": "KUBERNETES_POD_NAME","value": "1"}]}
const (
	addPodNameEnvPatch string = `[
		{ "op": "add", "path": "/spec/containers/- env/- KUBERNETES_POD_NAME", "value": "Always" }
	]`
)

type patchOperation struct {
	Op    string      `json:"op"`
	Path  string      `json:"path"`
	Value interface{} `json:"value,omitempty"`
}

func Container(added []corev1.Container, basePath string) (patch []patchOperation) {

	patch = append(patch, patchOperation{
		Op:    "add",
		Path:  basePath,
		Value: added,
	})
	return patch
}

func addEnv(ar v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
	klog.V(2).Info("mutating pods")
	podResource := metav1.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
	if ar.Request.Resource != podResource {
		klog.Errorf("expect resource to be %s", podResource)
		return nil
	}

	raw := ar.Request.Object.Raw
	pod := corev1.Pod{}
	deserializer := codecs.UniversalDeserializer()
	if _, _, err := deserializer.Decode(raw, nil, &pod); err != nil {
		klog.Error(err)
		return toAdmissionResponse(err)
	}
	reviewResponse := v1beta1.AdmissionResponse{}
	reviewResponse.Allowed = true
	//n := pod.Name
	Containers := pod.Spec.Containers
	for i := 0; i < len(Containers); i++ {
		klog.Info("容器名称：" + Containers[i].Name)
		ObjectFieldSelector := corev1.ObjectFieldSelector{"v1", "metadata.name"}
		EnvVarSource := corev1.EnvVarSource{&ObjectFieldSelector, nil, nil, nil}
		e := corev1.EnvVar{"POD_ID", "", &EnvVarSource}
		Containers[i].Env = append(Containers[i].Env, e)
	}

	patch := Container(pod.Spec.Containers, "/spec/containers")
	patchBytes, err := json.Marshal(patch)
	klog.Info(pod.Name + "修改成功")
	//klog.Info(string(patchBytes))

	if err != nil {
		return &v1beta1.AdmissionResponse{
			Result: &metav1.Status{
				Message: err.Error(),
			},
		}
	}
	reviewResponse.Patch = patchBytes
	pt := v1beta1.PatchTypeJSONPatch
	reviewResponse.PatchType = &pt
	return &reviewResponse
}
